package main

import (
	"fmt"
	"os"
	"os/exec"
	"strings"
	"time"
)

func RunCmd(name string, arg ...string) {
	cmd := exec.Command(name, arg...)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err := cmd.Run()
	if err != nil {
		fmt.Println("启动应用：", name, "失败！", err.Error())
	}
}

func RunDingbot() {
	RunCmd("./dingbot")
}

func RunGoCqhttp() {
	cmd := exec.Command("./go-cqhttp")
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Dir = "/dingbot_bin/bot/"
	err := cmd.Run()
	if err != nil {
		fmt.Println("启动应用：", "go-cqhttp", "失败！", err.Error())
	}
}

func FileExist(_path string) bool {
	_, err := os.Stat(_path)
	return err == nil
}

func main() {
	fmt.Print("dingbot_docker_runner将在稍后启动，请输入start以启动dingbot_docker:")
	var s string
	fmt.Scan(&s)
	if s != "start" {
		fmt.Println("输入错误！请重启docker compose")
		os.Exit(1)
	}
	DefaultConfig = strings.ReplaceAll(DefaultConfig, "{{Debug}}", os.Getenv("DebugMode"))
	DefaultConfig = strings.ReplaceAll(DefaultConfig, "{{User}}", os.Getenv("UserName"))
	DefaultConfig = strings.ReplaceAll(DefaultConfig, "{{Pass}}", os.Getenv("PassWord"))
	DefaultConfig = strings.ReplaceAll(DefaultConfig, "{{Avatar}}", os.Getenv("Avatar"))
	DefaultConfig = strings.ReplaceAll(DefaultConfig, "{{Token}}", os.Getenv("Token"))
	DefaultConfig = strings.ReplaceAll(DefaultConfig, "{{PocketUser}}", os.Getenv("PocketUser"))
	DefaultConfig = strings.ReplaceAll(DefaultConfig, "{{PocketPass}}", os.Getenv("PocketPass"))
	fmt.Println("生成配置：", DefaultConfig)
	os.WriteFile("config.json", []byte(DefaultConfig), 0777)
	DefaultGocqhttpConfig = strings.ReplaceAll(DefaultGocqhttpConfig, "{{QQ}}", os.Getenv("QQ"))
	DefaultGocqhttpConfig = strings.ReplaceAll(DefaultGocqhttpConfig, "{{QQPass}}", os.Getenv("QQPass"))
	fmt.Println("生成Gocqhttp配置：", DefaultGocqhttpConfig)
	os.WriteFile("bot/config.yml", []byte(DefaultGocqhttpConfig), 0777)
	if !FileExist("gocqhttp.lock") {
		fmt.Println("初次启动dingbot，请先登录成功机器人，然后重新docker compose up")
		fmt.Println("如果此次没有成功登录，需要将容器rebuild，即docker compose build")
		os.WriteFile("gocqhttp.lock", []byte(time.Now().String()), 0777)
		RunGoCqhttp()
		return
	}
	go func() {
		RunDingbot()
	}()
	time.Sleep(5 * time.Second)
	RunGoCqhttp()
}
